package com.cookor.poi.modules.weixin.service;

import com.cookor.poi.common.persistence.Page;
import com.cookor.poi.common.service.CrudService;
import com.cookor.poi.modules.weixin.dao.WeixinUserDao;
import com.cookor.poi.modules.weixin.entity.WeixinUser;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class WeixinUserService extends CrudService<WeixinUserDao, WeixinUser> {

	public WeixinUser getByOpenid(String appid, String openid) {
		WeixinUser user = new WeixinUser();
		user.setAppid(appid);
		user.setOpenid(openid);
		List<WeixinUser> list = dao.findList(user);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}

	}

	public static WeixinUser jsonToWeixinUser(JSONObject jsonObject) {
		return JSONUtil.toBean(jsonObject, WeixinUser.class);
	}

	public WeixinUser getByOpenid(String openid) {
		WeixinUser user = new WeixinUser();
		user.setOpenid(openid);
		List<WeixinUser> list = dao.findList(user);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}

	}

	public WeixinUser getByUnionid(String appid, String unionid) {
		WeixinUser user = new WeixinUser();
		user.setAppid(appid);
		user.setUnionid(unionid);
		List<WeixinUser> list = dao.findList(user);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	@Transactional(readOnly = false)
	public void saveUser(WeixinUser user) {
		WeixinUser temp = getByOpenid(user.getOpenid());
		if (temp != null) {
			user.setId(temp.getId());
		}
		save(user);
	}

	public WeixinUser get(String id) {
		return dao.get(id);
	}

	public List<WeixinUser> find(WeixinUser weixinUser) {

		return super.findList(weixinUser);
	}

	public Page<WeixinUser> find(Page<WeixinUser> page, WeixinUser weixinUser) {
		return super.findPage(page, weixinUser);
	}
}
